package com.example.midicontrol.midi

import android.media.midi.MidiDevice
import android.media.midi.MidiDeviceInfo
import android.media.midi.MidiManager
import android.media.midi.MidiOutputPort
import android.media.midi.MidiReceiver
import android.os.Handler
import android.os.Looper

class MidiDeviceManager(private val midiManager: MidiManager) {

    private val connectedDevices = mutableListOf<MidiDevice>()
    private var inputReceiver: MidiReceiver? = null

    fun registerDeviceCallback(callback: (Boolean, MidiDeviceInfo) -> Unit) {
        midiManager.registerDeviceCallback(object : MidiManager.DeviceCallback() {
            override fun onDeviceAdded(info: MidiDeviceInfo) {
                Handler(Looper.getMainLooper()).post {
                    callback(true, info)
                }
            }

            override fun onDeviceRemoved(info: MidiDeviceInfo) {
                Handler(Looper.getMainLooper()).post {
                    callback(false, info)
                }
            }
        }, null)
    }

    fun openDevice(info: MidiDeviceInfo, onMessageReceived: (ByteArray) -> Unit) {
        midiManager.openDevice(info, { device ->
            val inputPort = device.openInputPort(0)
            inputPort.connect(object : MidiReceiver {
                override fun onSend(msg: ByteArray, offset: Int, count: Int, timestamp: Long) {
                    onMessageReceived(msg.copyOfRange(offset, offset + count))
                }
            })
            connectedDevices.add(device)
        }, null)
    }

    fun closeAllDevices() {
        connectedDevices.forEach { it.close() }
        connectedDevices.clear()
    }
}
